package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.constants.SmsConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 发送短信的工具类
 */
@Component
@Slf4j
public class SmsHelper {

    @Autowired
    private IAcsClient client;
    @Autowired
    private SmsProperties smsProps;

    /**
     * 发送短信的方法
     */
    public void sendSms(String phone,String code){
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(smsProps.getDomain());
        request.setVersion(smsProps.getVersion());
        request.setAction(smsProps.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_REGION_ID, smsProps.getRegionID());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME, smsProps.getSignName());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE, smsProps.getVerifyCodeTemplate());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{\""+smsProps.getCode()+"\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);

            //获取响应结果
            String data = response.getData();

            //转换Java对象
            Map dataMap = JsonUtils.toMap(data,String.class,String.class);

            if(dataMap.get(SmsConstants.SMS_RESPONSE_KEY_CODE).equals(SmsConstants.OK)
                && dataMap.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE).equals(SmsConstants.OK)){
                //发送成功
                log.info("【短信业务】短信发送成功");
            }else{
                //发送失败
                log.error("【短信业务】短信发送失败，原因："+dataMap.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE));
            }

        }  catch (Exception e) {
            e.printStackTrace();
            log.error("【短信业务】短信发送失败，原因："+e.getMessage());
        }
    }


}
